package com.mla.fastdfs.service;

import com.mla.fastdfs.commom.RedisConstant;
import com.mla.fastdfs.commom.UpLoadConstant;
import com.mla.fastdfs.mapper.UploadUpInfoMapper;
import com.mla.fastdfs.pojo.UploadUpInfo;
import com.mla.fastdfs.utils.DateUtil;
import com.mla.fastdfs.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;

@Service
@EnableScheduling
public class TimingService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MyAsyncService asyncService;
    @Autowired
    private UploadUpInfoMapper uploadUpInfoMapper;

    /**
     * 逐步对未上传的文件进行逐步操作
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void MonitorFileState() {
        Map<Object, Object> map = redisUtil.hmget(RedisConstant.TELE_DOWN);
        //获取当前有没有任务在下载
        boolean executing = redisUtil.hasKey(RedisConstant.TELE_EXECUTING);
        boolean upload = redisUtil.hasKey(RedisConstant.TELE_UPLOAD);

        //文件状态 0：待下载 1：下载中 2：下载完成,待上传 3：文件上传中 4：文件上传完成
        for (Object o : map.keySet()) {
            String key = (String) o;
            Integer state = (Integer) map.get(o);
            //当前没有执行中的任务，并且这条信息的状态为0（待下载），创建下载任务
            if (!executing && state.equals(0)) {
                String fileName = UUID.randomUUID().toString().replace("-", "") + key.substring(key.lastIndexOf("."));
                asyncService.downloadByNIO2(key, UpLoadConstant.zipPartUpload + "/" + UUID.randomUUID().toString().replace("-", ""), fileName);
                executing = true;
                continue;
            }
            //当前没有上传中的任务，并且这条信息状态为2，创建上传任务
            if (!upload && state.equals(2)) {
                saveFile(key);
                upload = true;
            }
        }
    }

    private void saveFile(String url) {
        url = url.replace("\\", "/");
        String path = url.substring(0, url.lastIndexOf("/"));
        String flag = path.substring(path.lastIndexOf("/") + 1);
        UploadUpInfo upInfo = new UploadUpInfo();
        upInfo.setFlag(flag);
        upInfo.setUid("1");
        upInfo.setGroupId(1);
        upInfo.setStartTime(DateUtil.getStrTime());
        upInfo.setCreateTime(DateUtil.getStrTime());
        upInfo.setFileUrl("文件正在处理...");
        uploadUpInfoMapper.insert(upInfo);

        redisUtil.hset(RedisConstant.TELE_DOWN, url, 3);
        redisUtil.set(RedisConstant.TELE_UPLOAD, flag);
        asyncService.filePart(url, upInfo);
    }
}
